package com.daxia.bumall.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.daxia.bumall.daobase.GenericDAOHibernate;
import com.daxia.bumall.dto.BrandDTO;
import com.daxia.bumall.model.Brand;
import com.daxia.bumall.support.Page;

@Repository
public class BrandDAO extends GenericDAOHibernate<Brand> {

    public List<Brand> find(BrandDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Brand n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            hql.append(" and n.name = ? ");
            paras.add(dto.getName());
        }					
        if (StringUtils.isNotBlank(dto.getSearchTerm())) {
        	hql.append(" and n.name like ? ");
            paras.add("%" + dto.getSearchTerm() + "%");
        }
        if (dto.getPinguanType() != null) {
        	hql.append(" and n.pinguanType = ? ");
        	paras.add(dto.getPinguanType());
        }
        if (StringUtils.isNotBlank(dto.getImportImageName())) {
        	hql.append(" and n.importImageName = ? ");
        	paras.add(dto.getImportImageName());
        }
        if (dto.getRecommend() != null) {
        	if (dto.getRecommend() == 1) {
	        	hql.append(" and n.recommend = ? ");
	        	paras.add(dto.getRecommend());
        	} else {
        		hql.append(" and (n.recommend is null or n.recommend = 0) ");
        	}
        }
        hql.append(" order by n.id desc ");
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public List<Brand> getBrandByIds(List<Long> ids) {
    	StringBuilder hql = new StringBuilder();
    	hql.append(" from Brand where id in(:ids) ");
    	Query query = getSession().createQuery(hql.toString());
    	query.setParameterList("ids", ids);
    	return query.list();
    }
    
    public Brand findOne(BrandDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<Brand> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

	public List<Brand> findAllBrandsByProductCategory(Long productCategoryId) {
		String hql = "select distinct n.brand from Product n where n.productCategory.id = ? ";
		return super.find(hql, new Object[] {productCategoryId}, null);
	}
}
